package admin

import (
	"context"
	"fmt"
	"time"

	"oil-station-backend/internal/model"
	"oil-station-backend/internal/svc"
	"oil-station-backend/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type GetSalesReportLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewGetSalesReportLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetSalesReportLogic {
	return &GetSalesReportLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *GetSalesReportLogic) GetSalesReport(req *types.ReportReq) (resp []types.SalesReport, err error) {
	// 解析日期
	startDate, err := time.Parse("2006-01-02", req.StartDate)
	if err != nil {
		return nil, fmt.Errorf("无效的开始日期格式，请使用YYYY-MM-DD格式")
	}

	endDate, err := time.Parse("2006-01-02", req.EndDate)
	if err != nil {
		return nil, fmt.Errorf("无效的结束日期格式，请使用YYYY-MM-DD格式")
	}

	// 确保结束日期不早于开始日期
	if endDate.Before(startDate) {
		return nil, fmt.Errorf("结束日期不能早于开始日期")
	}

	// 查询已完成的订单
	var orders []model.Order
	err = l.svcCtx.DB.Where("status = ? AND complete_time BETWEEN ? AND ?", 
		"completed", startDate, endDate.AddDate(0, 0, 1)).Find(&orders).Error
	if err != nil {
		return nil, err
	}

	// 按日期分组统计
	dateMap := make(map[string]*types.SalesReport)
	fuelTypeMap := make(map[string]map[string]*struct {
		Orders int64
		Amount float64
		Volume float64
	})

	for _, order := range orders {
		dateStr := order.CompleteTime.Format("2006-01-02")
		
		// 初始化日期报表
		if _, ok := dateMap[dateStr]; !ok {
			dateMap[dateStr] = &types.SalesReport{
				Date:         dateStr,
				TotalOrders:  0,
				TotalAmount:  0,
				TotalVolume:  0,
				FuelTypeData: []struct {
					FuelType string  `json:"fuelType"`
					Orders   int64   `json:"orders"`
					Amount   float64 `json:"amount"`
					Volume   float64 `json:"volume"`
				}{},
			}
		}

		// 初始化油品类型统计
		if _, ok := fuelTypeMap[dateStr]; !ok {
			fuelTypeMap[dateStr] = make(map[string]*struct {
				Orders int64
				Amount float64
				Volume float64
			})
		}

		if _, ok := fuelTypeMap[dateStr][order.FuelType]; !ok {
			fuelTypeMap[dateStr][order.FuelType] = &struct {
				Orders int64
				Amount float64
				Volume float64
			}{0, 0, 0}
		}

		// 更新统计数据
		report := dateMap[dateStr]
		report.TotalOrders++
		
		var actualAmount, actualVolume float64
		if order.ActualAmount != nil {
			actualAmount = *order.ActualAmount
		}
		if order.ActualVolume != nil {
			actualVolume = *order.ActualVolume
		}
		
		report.TotalAmount += actualAmount
		report.TotalVolume += actualVolume

		// 更新油品类型统计
		fuelData := fuelTypeMap[dateStr][order.FuelType]
		fuelData.Orders++
		fuelData.Amount += actualAmount
		fuelData.Volume += actualVolume
	}

	// 构建响应
	for dateStr, report := range dateMap {
		// 添加油品类型数据
		for fuelType, data := range fuelTypeMap[dateStr] {
			report.FuelTypeData = append(report.FuelTypeData, struct {
				FuelType string  `json:"fuelType"`
				Orders   int64   `json:"orders"`
				Amount   float64 `json:"amount"`
				Volume   float64 `json:"volume"`
			}{
				FuelType: fuelType,
				Orders:   data.Orders,
				Amount:   data.Amount,
				Volume:   data.Volume,
			})
		}

		resp = append(resp, *report)
	}

	return resp, nil
}